import store from "@/store/index.js";
import Vue from "vue";
import VueRouter from "vue-router";
import routes from "./routers.js";

Vue.use(VueRouter);
const originalPush = VueRouter.prototype.push;

//解决重复点击一个菜单，重复触发一个相同的路由问题
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err);
};

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
  //每次路由跳转页面都会滚动到y=0（页面顶部）的位置
  scrollBehavior:()=>({ y: 0 })
});

export default router;

router.beforeEach((to, from, next) => {
  //如果没有登录（store没有存储token）
  let hasToken = store.state.login.token;
  if (!hasToken) {
    if (
      to.path == "/shopCart" ||
      to.path == "/paying" ||
      to.path == "/center"
    ) {
      alert("你还未登录，点击确定去登录。");
      next("/login");
    } else {
      next();
    }
  } else {
    console.log("changeNickname", store.state.login.nickname);
    next();
  }
  // next()
});
